<!-- 帐单列表 -->
<template>
    <Card>
        <Row class="ivu-mb-16">
            <Col span="20">
            <DatePicker type="month" placeholder="请选择月份" v-model="month"  @on-change="changemonth" :options="options1" :clearable="false" style="width: 200px"></DatePicker>
            <Select v-model="net_config_id" style="width:200px" class="ivu-ml-16" placeholder="请选择营销中心" @on-change="changeSelect" clearable>
                <Option v-for="item in centerList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
            </Col>
            <Col span="4">
            <ButtonGroup>
                <Button type="warning"  @click="exportData"
                        v-hasC="{
                            name: '-282',
                            flag: '/',
                        }"
                >导出</Button>
                <Button type="primary" :disabled="editDisabled" @click="changeCreate"
                        v-hasC="{
                            name: '-v1-marketing-dingtalk-create-bill',
                            flag: '/v1/marketing/dingtalk/create-bill',
                        }"
                >生成对帐单</Button>
            </ButtonGroup>
            </Col>
        </Row>
        <Table row-key="id" :indent-size="0" :load-data="handleLoadData" :update-show-children="true" :columns="columns" :data="data" :loading="loading">
            <template slot-scope="{ row }" slot="amount">
                <span v-if="row.id==0">{{row.real_money}}</span>
                <a @click="changecount(row)" v-else>{{row.real_money}}</a>
      
            </template>
        </Table>
        <Modal v-model="modal" title="审批记录"  width="600" footer-hide>
            <Table :columns="modalcolumns" :data="modaldata"></Table>
        </Modal>
    </Card>
</template>
<script>
    import {monthBill,moneyList,createDill,monthbillCondition} from '@/api/hqapi/networkMarketing.js';
    import * as XLSX from 'xlsx';
    export default {
        data(){
            return {
                // month:this.$Date(new Date()).toJSON(),
                // month: this.$Date(new Date()).getMonth(),
                month: new Date(),
                net_config_id: null,
                centerList: [],
                columns: [
                    { title: '渠道', key: 'source_name', fixed: 'left', tree: true, minWidth: 150 },
                    { title: '上月余额', key: 'history_surplus_real_money', minWidth: 150 },
                    { title: '实批金额', slot: 'amount', minWidth: 150 },
                    { title: '本月返点金额', key: 'rebate_money', minWidth: 150 },
                    { title: '历史返点金额', key: 'history_rebate_money', minWidth: 150 },
                    { title: '营销费用', key: 'market_money', minWidth: 150 },
                    { title: '基建费用', key: 'construct_money', minWidth: 150 },
                    { title: '本月剩余', key: 'surplus_real_money', minWidth: 150 },
                ],
                data: [],
                allData: {},
                allDatas: {},
                dataHeader: [],
                dataHeaders: [],
                dataData: [],
                loading: false,
                modal: false,
                modalcolumns: [
                    { title: '申请人', key: 'realname', width: 150 },
                    { title: '实批金额', key: 'real_money', width: 150 },
                    { title: '返点金额', key: 'rebate_money', width: 100 },
                    { title: '审批日期', key: 'finish_time_str', minWidth: 100 },
                ],
                modaldata: [],
                options1: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
                editDisabled: false
            };
        },
        mounted() {
            let lastmonth = this.$Date().subtract(1, 'month').format('YYYY-MM');
            // console.log(lastmonth,'lastmonth')
            let newmonth = this.$Date().format('YYYY-MM');
            // console.log(this.$Date().format('YYYY-MM')==newmonth,'222')
            //  console.log(lastmonth==this.$Date().format('YYYY-MM'),'111')
            if(lastmonth == this.$Date().format('YYYY-MM') || this.$Date().format('YYYY-MM') == newmonth){
                this.editDisabled = false;
            }else {
                this.editDisabled = true;
            }
        },
        methods: {
            // 判断日期时候近2个月
            datemonth(){
                let lastmonth = this.$Date().subtract(1, 'month').format('YYYY-MM');
                let newmonth = this.$Date().format('YYYY-MM');
                if(lastmonth == this.$Date().format('YYYY-MM') || this.$Date().format('YYYY-MM') == newmonth){
                    this.editDisabled = false;
                }else {
                    this.editDisabled = true;
                }
            },
            initial(){
                this.datemonth();
                this.getlist();
                this._getmonthbillCondition()
            },
            //获取营销报表
            _getmonthbillCondition(){
                monthbillCondition().then(res=>{
                    this.centerList=res.config
                })
            },
            changemonth(){
                let lastmonth = this.$Date().subtract(1, 'month').format('YYYY-MM');
                let newmonth = this.$Date().format('YYYY-MM');
                // console.log(this.$Date(this.month).format('YYYY-MM'),'222')
                // console.log(lastmonth==this.$Date().format('YYYY-MM'),'111')
                if(lastmonth == this.$Date(this.month).format('YYYY-MM') || this.$Date(this.month).format('YYYY-MM') == newmonth){
                    this.editDisabled = false;
                }else {
                    this.editDisabled = true;
                }
                this.getlist();
            },
            changeSelect(val){
                this.net_config_id=val
                this.getlist();
            },
            // 获取帐单列表
            getlist(){
                monthBill({month: this.$Date(this.month).format('YYYY-MM'),net_config_id:this.net_config_id}).then(res => {
                    this.data = [];
                    this.dataHeader = [];
                    this.dataHeaders = [];
                    this.dataData = res.list;
                    if(res.list){
                        res.list.forEach(item => {
                            if(item.source_name !== '合计') {
                                this.dataHeader.push(item.source_name);
                            }
                            this.allData[item.id] = item.children;
                            this.allDatas[item.source_name] = item.children;
                            this.dataHeaders[item.source_name] = {
                                source_name: '总计',
                                history_surplus_real_money: item.history_surplus_real_money,
                                real_money: item.real_money,
                                rebate_money: item.rebate_money,
                                history_rebate_money: item.history_rebate_money,
                                market_money: item.market_money,
                                construct_money: item.construct_money,
                                surplus_real_money: item.surplus_real_money,
                            };
                            if(item.children) {
                                this.data.push({
                                    _loading: false,
                                    source_name: item.source_name,
                                    history_surplus_real_money: item.history_surplus_real_money,
                                    real_money: item.real_money,
                                    rebate_money: item.rebate_money,
                                    history_rebate_money: item.history_rebate_money,
                                    market_money: item.market_money,
                                    construct_money: item.construct_money,
                                    surplus_real_money: item.surplus_real_money,
                                    children: [],
                                    id: item.id,
                                });
                            }else {
                                this.data.push({
                                    source_name: item.source_name,
                                    history_surplus_real_money: item.history_surplus_real_money,
                                    real_money: item.real_money,
                                    rebate_money: item.rebate_money,
                                    history_rebate_money: item.history_rebate_money,
                                    market_money: item.market_money,
                                    construct_money: item.construct_money,
                                    surplus_real_money: item.surplus_real_money,
                                    id: item.id,
                                });
                            }
                        });
                    }
    
                    this.loading = false;
                });
            },
            handleLoadData(item, callback) {
                //  console.log(item,'item')
                item._loading = true;
                setTimeout(() => {
                    const data = this.allData[item.id];
                    // console.log(data,'data')
                    callback(data);
                });
            },
            changecount(row){
                if(row.id == 0){
                    this.modal = false;
                }else {
                    this.getdetails(row);
                    this.modal = true;
                }
                // console.log(row,'row')
     
            },
            // 审批记录
            getdetails(row){
                const params = {
                    month: this.$Date(this.month).format('YYYY-MM'),
                    channel_id: row.pid ? row.pid : row.id,
                    subdivided_channels_id: row.pid ? row.id : '',
                    page: 0,
                    pageSize: 0
                };
                moneyList(params).then(res => {
                    this.modaldata = res.list;
                });
            },
            exportData() {
                // if (this.datas.length > 0) {
                //     this.$refs.tables.exportCsv({
                //         filename: '营销报表'
                //     });
                // } else {
                //     this.$Message.error('暂无数据');
                // }
                const wb = XLSX.utils.book_new();
                let data = this.dataData.map(item => {
                    return {
                        渠道: item.source_name,
                        上月余额: item.history_surplus_real_money,
                        实批金额: item.real_money,
                        本月返点金额: item.rebate_money,
                        历史返点金额: item.history_rebate_money,
                        营销费用: item.market_money,
                        基建费用: item.construct_money,
                        本月剩余: item.arrived_rate,
                    }; 
                });
                let datas = XLSX.utils.json_to_sheet(data);
                XLSX.utils.book_append_sheet(wb, datas, '总表');
                this.dataHeader.forEach(events => {
                    let data1 = this.allDatas[events].map(item => {
                        return {
                            渠道: item.source_name,
                            上月余额: item.history_surplus_real_money,
                            实批金额: item.real_money,
                            本月返点金额: item.rebate_money,
                            历史返点金额: item.history_rebate_money,
                            营销费用: item.market_money,
                            基建费用: item.construct_money,
                            本月剩余: item.arrived_rate,
                        }; 
                    });
                    data1.push({
                        渠道: this.dataHeaders[events].source_name,
                        上月余额: this.dataHeaders[events].history_surplus_real_money,
                        实批金额: this.dataHeaders[events].real_money,
                        本月返点金额: this.dataHeaders[events].rebate_money,
                        历史返点金额: this.dataHeaders[events].history_rebate_money,
                        营销费用: this.dataHeaders[events].market_money,
                        基建费用: this.dataHeaders[events].construct_money,
                        本月剩余: this.dataHeaders[events].arrived_rate,
                    });
                    let data2 = XLSX.utils.json_to_sheet(data1);
                    XLSX.utils.book_append_sheet(wb, data2, events);
                });
                const workbookBlob = this.workbook2blob(wb);
                this.openDownloadDialog(workbookBlob, '对帐报表.xlsx');
            },
            // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
            workbook2blob(workbook) {
                // 生成excel的配置项
                var wopts = {
                    // 要生成的文件类型
                    bookType: 'xlsx',
                    // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                    bookSST: false,
                    // 二进制类型
                    type: 'binary'
                };
                var wbout = XLSX.write(workbook, wopts);
                var blob = new Blob([this.s2ab(wbout)], {
                    type: 'application/octet-stream'
                });
                return blob;
            },

            // 将字符串转ArrayBuffer
            s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for(var i = 0; i != s.length; ++i) {
                    view[i] = s.charCodeAt(i) & 0xff;
                }
                return buf;
            },

            // 将blob对象创建bloburl，然后用a标签实现弹出下载框
            openDownloadDialog(blob, fileName) {
                if(typeof blob === 'object' && blob instanceof Blob) {
                    blob = URL.createObjectURL(blob); // 创建blob地址
                }
                var aLink = document.createElement('a');
                aLink.href = blob;
                // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
                aLink.download = fileName || '';
                var event;
                if(window.MouseEvent) event = new MouseEvent('click');
                //   移动端
                else {
                    event = document.createEvent('MouseEvents');
                    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                }
                aLink.dispatchEvent(event);
                URL.revokeObjectURL(blob);
            },
            // 生成对帐单
            changeCreate(){
                // console.log(this.$Date(this.month).format('YYYY-MM'),'this.month',this.month)
                createDill({month: this.$Date(this.month).format('YYYY-MM'),net_config_id:this.net_config_id}).then(res => {
                    this.$Notice.success({
                        title: '',
                        desc: '已生成账单，请到生成记录列表查看',
                        // render: h => {
                        //     return h('span', [
                        //         'This is created by ',
                        //         h('a', 'render'),
                        //         ' function'
                        //     ])
                        // }
                    });

                });
            }
        }
    };
</script>